package com.example.musicaiap.data.database.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.example.musicaiap.data.database.PlaylistEntity
import com.example.musicaiap.data.database.PlaylistWithSongs
import kotlinx.coroutines.flow.Flow

/**
 * 播放列表数据访问对象
 * 定义对播放列表表的各种数据库操作
 */
@Dao
interface PlaylistDao {
    
    /**
     * 插入一个播放列表
     * 如果ID已存在，则替换
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertPlaylist(playlist: PlaylistEntity)
    
    /**
     * 批量插入播放列表
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertPlaylists(playlists: List<PlaylistEntity>)
    
    /**
     * 更新播放列表
     */
    @Update
    suspend fun updatePlaylist(playlist: PlaylistEntity)
    
    /**
     * 获取所有播放列表
     */
    @Query("SELECT * FROM playlists ORDER BY updatedAt DESC")
    suspend fun getAllPlaylists(): List<PlaylistEntity>
    
    /**
     * 获取所有播放列表（Flow版本）
     */
    @Query("SELECT * FROM playlists ORDER BY updatedAt DESC")
    fun getAllPlaylistsFlow(): Flow<List<PlaylistEntity>>
    
    /**
     * 根据ID获取播放列表
     */
    @Query("SELECT * FROM playlists WHERE id = :playlistId")
    suspend fun getPlaylistById(playlistId: String): PlaylistEntity?
    
    /**
     * 获取本地音乐播放列表
     */
    @Query("SELECT * FROM playlists WHERE isLocal = 1 LIMIT 1")
    suspend fun getLocalPlaylist(): PlaylistEntity?
    
    /**
     * 获取收藏音乐播放列表
     */
    @Query("SELECT * FROM playlists WHERE id = 'favorites' LIMIT 1")
    suspend fun getFavoritePlaylist(): PlaylistEntity?
    
    /**
     * 获取收藏音乐播放列表（非挂起版本）
     */
    @Query("SELECT * FROM playlists WHERE id = 'favorites' LIMIT 1")
    fun getFavoritePlaylistSync(): PlaylistEntity?
    
    /**
     * 删除播放列表
     */
    @Query("DELETE FROM playlists WHERE id = :playlistId")
    suspend fun deletePlaylist(playlistId: String)
    
    /**
     * 获取包含歌曲的播放列表（一对多关系）
     */
    @Transaction
    @Query("SELECT * FROM playlists WHERE id = :playlistId")
    suspend fun getPlaylistWithSongs(playlistId: String): PlaylistWithSongs?
    
    /**
     * 获取所有包含歌曲的播放列表（一对多关系）
     */
    @Transaction
    @Query("SELECT * FROM playlists ORDER BY updatedAt DESC")
    suspend fun getAllPlaylistsWithSongs(): List<PlaylistWithSongs>
} 